import React, { PropsWithChildren, useCallback, useRef } from 'react'
import {
  Text, View, Image,
} from 'react-native'
import EStyleSheet from 'react-native-extended-stylesheet'
import LinearGradientButton from '@COMPONENTS/button/LinearGradient'
import Images from '@IMAGE'
import Portal from '@COMPONENTS/portal'
import Modal from '@COMPONENTS/modal/Modal'
import Button from '@COMPONENTS/button/Button'
import ViewShot from 'react-native-view-shot'
import { CameraRoll } from '@react-native-camera-roll/camera-roll'
import Toast from '@COMPONENTS/Toast'
import { isAndroid } from '@UTILS/Common'
import Permissions from '@UTILS/Permissions'

const ModalCom: React.FC<{ onClose?: (() => void) | undefined; }> = ({ onClose }) => {
  const ref = useRef<PropsWithChildren<ViewShot>>(null)
  const onSave = () => {
    ref.current?.capture?.().then(async (res) => {
      console.log('res', res)
      const result = await CameraRoll.save(res, { type: 'photo' })
      console.log('result', result)
      Toast.info('保存成功')
    }).catch(() => {
      Toast.info('保存失败')
    }).finally(() => {
      onClose?.()
    })
  }
  const handleSave = async () => {
    if (isAndroid) {
      const hasPermission = await Permissions.requestAndroidFilePermission()
      if (hasPermission) {
        onSave()
      } else {
        onClose?.()
        Toast.info('需要允许权限使用该功能')
      }
    } else {
      onSave()
    }
  }
  const onRequestClose = useCallback(() => {
    onClose?.()
    return true
  }, [onClose])
  return (
    <Modal
      visible
      onClose={onClose}
      animationType="fade"
      onRequestClose={onRequestClose}
    >
      <View style={styles.bodyStyle}>
        <ViewShot ref={ref} options={{ result: 'tmpfile' }}>
          <Image source={Images.home.qrCode} style={styles.image} />
        </ViewShot>
        <Text style={styles.pauseCount}>保存图片到相册，微信扫码添加客服企微</Text>
        <View style={styles.footer}>
          <Button onPress={onClose} style={styles.btnContainer}>
            <Text style={styles.leftButton}>关闭</Text>
          </Button>
          <LinearGradientButton style={[styles.btnContainer, styles.linearGradientButton]} onPress={handleSave}>
            <Image source={Images.home.iconDownload} />
            <Text style={[styles.leftButton, styles.rightButton]}>
              保存图片
            </Text>
          </LinearGradientButton>
        </View>
      </View>
    </Modal>
  )
}

export default {
  show: () => {
    const key = Portal.add(
      <ModalCom
        onClose={() => {
          Portal.remove(key)
        }}
      />,
    )
    return key
  },
}
const styles = EStyleSheet.create({
  bodyStyle: {
    width: 295,
    backgroundColor: '$white',
    borderRadius: 12,
    paddingHorizontal: 16,
    paddingVertical: 24,
    justifyContent: 'center',
    alignItems: 'center',
  },
  image: {
    marginTop: 8,
    marginBottom: 28,
  },
  pauseCount: {
    fontSize: 14,
    lineHeight: 24,
    marginBottom: 48,
    fontFamily: 'PingFangSC-Regular',
    color: '$common',
  },
  desc: {
    fontSize: 12,
    fontFamily: 'PingFangSC-Regular',
    fontWeight: '400',
    color: '#595959',
    marginTop: 8,
    marginBottom: 48,
  },
  footer: {
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  leftButton: {
    fontSize: 15,
    fontFamily: 'PingFangSC-Medium',
    fontWeight: '500',
    color: '#595959',
    textAlign: 'center',
  },
  rightButton: {
    color: '$white',
    backgroundColor: 'transparent',
    borderColor: 'transparent',
    marginLeft: 12,
  },
  btnContainer: {
    width: 120,
    paddingVertical: 12,
    borderRadius: 23,
    borderColor: '#D0D4DB',
    borderWidth: 1,
    backgroundColor: '$white',
  },
  linearGradientButton: {
    width: 120,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: 'transparent',
    borderRadius: 23,
  },
})
